{% extends "member/layout.html" %}

{% block title %}创建新任务{% endblock %}

{% block content %}
<div class="d-flex flex-column h-100">
    <!-- 页面标题区域 - 优化视觉层次 -->
    <div class="mb-4">
        <div class="d-flex align-items-center justify-content-between">
            <div>
                <h2 class="h3 fw-bold mb-1">
                    <i class="fas fa-plus-circle me-2 text-primary"></i>创建新任务
                </h2>
                <p class="text-muted mb-0">为项目创建新任务，分配负责人并设置截止日期</p>
            </div>
            {% if request.args.get('project_id') %}
            <a href="{{ url_for('member.jira.project_detail', project_id=request.args.get('project_id')) }}"
               class="btn btn-outline-secondary rounded-pill">
                <i class="fas fa-arrow-left me-2"></i>返回项目
            </a>
            {% else %}
            <a href="{{ url_for('member.jira.list_projects') }}"
               class="btn btn-outline-secondary rounded-pill">
                <i class="fas fa-arrow-left me-2"></i>返回项目列表
            </a>
            {% endif %}
        </div>
        <hr class="mt-3 mb-0">
    </div>

    <!-- 任务创建表单 - 优化布局和视觉设计 -->
    <div class="dashboard-card flex-grow-1">
        <div class="card-body p-4 h-100">
            <div class="row h-100 g-0">
                <!-- 左侧：表单区域 - 添加卡片式设计 -->
                <div class="col-lg-7 pe-lg-4 border-end border-light">
                    <div class="bg-white rounded-lg p-4 shadow-sm">
                        <form method="post" id="taskForm" class="h-100 d-flex flex-column">
                            {{ form.csrf_token }}
                            <input type="hidden" name="project_id" value="{{ request.args.get('project_id') or '' }}">

                            <!-- 任务名称 - 增强输入框样式 -->
                            <div class="mb-4">
                                <label for="name" class="form-label fw-semibold mb-2">
                                    <i class="fas fa-tag me-2 text-primary"></i>任务名称
                                    <span class="text-danger">*</span>
                                </label>
                                <input type="text" class="form-control form-control-lg bg-light" id="name" name="name"
                                       placeholder="请输入任务名称" required>
                                <div class="form-text mt-2">
                                    <i class="fas fa-info-circle me-1"></i>请使用简洁明了的任务名称，便于识别和管理
                                </div>
                            </div>

                            <!-- 任务描述 - 优化文本区域样式 -->
                            <div class="mb-4">
                                <label for="description" class="form-label fw-semibold mb-2">
                                    <i class="fas fa-file-alt me-2 text-primary"></i>任务描述
                                </label>
                                <textarea class="form-control form-control-lg bg-light" id="description" name="description"
                                          rows="4" placeholder="请详细描述任务内容、要求和注意事项..."></textarea>
                                <div class="d-flex justify-content-between align-items-center mt-2">
                                    <div class="form-text">
                                        <i class="fas fa-lightbulb me-1"></i>清晰的描述有助于负责人理解任务要求
                                    </div>
                                    <div class="text-muted small">
                                        <span id="charCount">0</span>/500
                                    </div>
                                </div>
                            </div>

                            <!-- 附件上传 - 优化上传区域样式 -->
                            <div class="mb-4">
                                <label class="form-label fw-semibold mb-2">
                                    <i class="fas fa-paperclip me-2 text-primary"></i>任务附件
                                </label>
                                <div class="file-upload-area border rounded-3 p-3 bg-light">
                                    <div class="d-flex flex-column align-items-center justify-content-center py-4">
                                        <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
                                        <h6 class="mb-2">拖放文件到此处或点击上传</h6>
                                        <p class="text-muted small mb-3">支持单个或多个文件上传</p>
                                        <button type="button" class="btn btn-sm btn-primary rounded-pill" id="selectFilesBtn">
                                            <i class="fas fa-folder-open me-1"></i>选择文件
                                        </button>
                                    </div>
                                    <input type="file" class="d-none" id="fileInput" name="files" multiple>
                                    <div class="file-preview mt-3" id="filePreview"></div>
                                </div>
                            </div>

                            <!-- 负责人和截止日期 - 优化布局 -->
                            <div class="row mb-4">
                                <div class="col-md-6">
                                    <label for="assignee_id" class="form-label fw-semibold mb-2">
                                        <i class="fas fa-user-check me-2 text-primary"></i>负责人
                                    </label>
                                    <select class="form-select form-select-lg bg-light" id="assignee_id" name="assignee_id">
                                        <option value="">-- 请选择负责人 --</option>
                                        {% for member in members %}
                                        <option value="{{ member.id }}">{{ member.name }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label for="due_date" class="form-label fw-semibold mb-2">
                                        <i class="fas fa-calendar-day me-2 text-primary"></i>截止日期
                                    </label>
                                    <input type="date" class="form-control form-control-lg bg-light" id="due_date" name="due_date">
                                </div>
                            </div>

                            <!-- 任务优先级 - 优化按钮样式 -->
                            <div class="mb-4">
                                <label class="form-label fw-semibold mb-2">
                                    <i class="fas fa-flag me-2 text-primary"></i>任务优先级
                                </label>
                                <div class="priority-selector">
                                    <div class="row g-2">
                                        <div class="col-md-4">
                                            <input type="radio" class="btn-check" name="priority" id="priority-low" value="low" checked>
                                            <label class="btn btn-outline-success w-100 d-flex align-items-center justify-content-center rounded-pill" for="priority-low">
                                                <i class="fas fa-arrow-down me-2"></i>低优先级
                                            </label>
                                        </div>
                                        <div class="col-md-4">
                                            <input type="radio" class="btn-check" name="priority" id="priority-medium" value="medium">
                                            <label class="btn btn-outline-warning w-100 d-flex align-items-center justify-content-center rounded-pill" for="priority-medium">
                                                <i class="fas fa-minus me-2"></i>中优先级
                                            </label>
                                        </div>
                                        <div class="col-md-4">
                                            <input type="radio" class="btn-check" name="priority" id="priority-high" value="high">
                                            <label class="btn btn-outline-danger w-100 d-flex align-items-center justify-content-center rounded-pill" for="priority-high">
                                                <i class="fas fa-arrow-up me-2"></i>高优先级
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 操作按钮 - 优化按钮样式 -->
                            <div class="mt-auto pt-4">
                                <div class="d-flex justify-content-end gap-3">
                                    <button type="reset" class="btn btn-light px-4 rounded-pill">
                                        <i class="fas fa-redo me-2"></i>重置
                                    </button>
                                    <button type="submit" class="btn btn-primary px-4 rounded-pill">
                                        <i class="fas fa-plus-circle me-2"></i>创建任务
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- 右侧：预览区域 - 优化卡片样式 -->
                <div class="col-lg-5 ps-lg-4">
                    <div class="sticky-top" style="top: 100px;">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5 class="fw-bold mb-0">
                                <i class="fas fa-eye me-2 text-primary"></i>任务预览
                            </h5>
                            <button type="button" class="btn btn-sm btn-outline-primary rounded-pill" id="togglePreview">
                                <i class="fas fa-sync-alt me-1"></i>刷新预览
                            </button>
                        </div>

                        <div class="preview-container bg-white rounded-lg p-4 shadow-sm">
                            <div class="preview-content">
                                <!-- 任务标题预览 -->
                                <div class="d-flex align-items-center mb-3 pb-3 border-bottom">
                                    <div class="flex-shrink-0">
                                        <div class="avatar-sm bg-primary bg-opacity-10 text-primary rounded-circle d-flex align-items-center justify-content-center me-3">
                                            <i class="fas fa-tasks"></i>
                                        </div>
                                    </div>
                                    <div class="flex-grow-1">
                                        <h6 class="fw-bold mb-1" id="previewName">任务名称</h6>
                                        <span class="badge bg-success" id="previewPriority">低优先级</span>
                                    </div>
                                </div>

                                <!-- 任务详情预览 -->
                                <div class="mb-3">
                                    <p class="text-muted small mb-2">任务描述</p>
                                    <p class="mb-0" id="previewDescription">暂无任务描述</p>
                                </div>

                                <!-- 任务元信息 -->
                                <div class="row g-2">
                                    <div class="col-6">
                                        <div class="bg-light rounded p-2 border">
                                            <p class="text-muted small mb-1">负责人</p>
                                            <p class="fw-medium mb-0" id="previewAssignee">未选择</p>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="bg-light rounded p-2 border">
                                            <p class="text-muted small mb-1">截止日期</p>
                                            <p class="fw-medium mb-0" id="previewDueDate">未设置</p>
                                        </div>
                                    </div>
                                </div>

                                <!-- 状态指示器 -->
                                <div class="mt-3 pt-3 border-top">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <div class="avatar-xs bg-secondary bg-opacity-10 text-secondary rounded-circle d-flex align-items-center justify-content-center">
                                                <i class="fas fa-clock"></i>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 ms-2">
                                            <p class="small text-muted mb-0">任务状态: <span class="fw-medium">待开始</span></p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 提示信息 -->
                        <div class="mt-3">
                            <div class="alert alert-info border-0 py-2">
                                <div class="d-flex align-items-center">
                                    <i class="fas fa-info-circle me-2"></i>
                                    <small>填写表单时，右侧预览将实时更新</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    /* 增强输入框样式 */
    .form-control-lg, .form-select-lg {
        border-radius: 12px;
        border: 1px solid #e2e8f0;
        padding: 0.85rem 1.25rem;
        transition: all 0.3s;
        box-shadow: 0 2px 4px rgba(0,0,0,0.02);
    }

    .form-control-lg:focus, .form-select-lg:focus {
        border-color: #4361ee;
        box-shadow: 0 0 0 0.25rem rgba(67, 97, 238, 0.15);
    }

    /* 优化标签样式 */
    .form-label {
        color: #374151;
        font-size: 0.95rem;
        font-weight: 500;
    }

    /* 预览容器样式 */
    .preview-container {
        border-left: 4px solid #4361ee;
        min-height: 300px;
        transition: all 0.3s ease;
        border-radius: 12px;
    }

    /* 按钮样式 */
    .btn {
        border-radius: 8px;
        font-weight: 500;
        padding: 0.65rem 1.5rem;
        transition: all 0.2s;
    }

    .btn-primary {
        background-color: #4361ee;
        border-color: #4361ee;
    }

    .btn-primary:hover {
        background-color: #3a56d4;
        border-color: #3a56d4;
    }

    /* 优先级按钮样式 */
    .priority-selector .btn {
        padding: 0.85rem 0.5rem;
        border-radius: 50px;
        font-weight: 600;
        transition: all 0.3s;
    }

    .priority-selector .btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }

    /* 头像样式 */
    .avatar-sm {
        width: 45px;
        height: 45px;
        font-size: 1.1rem;
    }

    .avatar-xs {
        width: 32px;
        height: 32px;
        font-size: 0.9rem;
    }

    /* 响应式调整 */
    @media (max-width: 991.98px) {
        .border-end {
            border-right: none !important;
            border-bottom: 1px solid rgba(0,0,0,.1) !important;
            padding-bottom: 2rem;
            margin-bottom: 2rem;
        }

        .ps-lg-4 {
            padding-left: 0 !important;
        }

        .pe-lg-4 {
            padding-right: 0 !important;
        }

        .row.g-0 > .col-lg-7, .row.g-0 > .col-lg-5 {
            padding-left: 0 !important;
            padding-right: 0 !important;
        }
    }

    /* 粘性顶部边距 */
    .sticky-top {
        top: 100px;
        z-index: 10;
    }

    /* 文件上传区域样式 */
    .file-upload-area {
        transition: all 0.3s;
        border: 2px dashed #e2e8f0;
    }

    .file-upload-area:hover {
        border-color: #4361ee;
        background-color: #f8f9fe;
    }

    /* 文件预览项样式 */
    .file-preview-item {
        transition: all 0.2s;
        border-radius: 8px;
    }

    .file-preview-item:hover {
        background-color: #f8f9fe;
        transform: translateX(5px);
    }

    /* 阴影效果 */
    .hover-shadow {
        transition: all 0.3s;
    }

    .hover-shadow:hover {
        box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        transform: translateY(-2px);
    }
</style>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 元素引用
        const nameInput = document.getElementById('name');
        const descriptionTextarea = document.getElementById('description');
        const assigneeSelect = document.getElementById('assignee_id');
        const dueDateInput = document.getElementById('due_date');
        const previewName = document.getElementById('previewName');
        const previewDescription = document.getElementById('previewDescription');
        const previewAssignee = document.getElementById('previewAssignee');
        const previewDueDate = document.getElementById('previewDueDate');
        const previewPriority = document.getElementById('previewPriority');
        const charCount = document.getElementById('charCount');
        const priorityRadios = document.querySelectorAll('input[name="priority"]');
        const togglePreview = document.getElementById('togglePreview');
        const fileInput = document.getElementById('fileInput');
        const selectFilesBtn = document.getElementById('selectFilesBtn');
        const filePreview = document.getElementById('filePreview');
        const fileUploadArea = document.querySelector('.file-upload-area');

        // 字符计数
        descriptionTextarea.addEventListener('input', function() {
            const count = this.value.length;
            charCount.textContent = count;
            charCount.classList.toggle('text-danger', count > 500);
            updatePreview();
        });

        // 刷新预览按钮
        togglePreview.addEventListener('click', updatePreview);

        // 实时更新预览
        function updatePreview() {
            // 更新任务名称预览
            previewName.textContent = nameInput.value || '任务名称';

            // 更新任务描述预览
            const desc = descriptionTextarea.value;
            previewDescription.textContent = desc ?
                (desc.length > 120 ? desc.substring(0, 120) + '...' : desc) : '暂无任务描述';

            // 更新负责人预览
            const selectedAssignee = assigneeSelect.options[assigneeSelect.selectedIndex];
            previewAssignee.textContent = selectedAssignee.text || '未选择';

            // 更新截止日期预览
            previewDueDate.textContent = dueDateInput.value ?
                new Date(dueDateInput.value).toLocaleDateString('zh-CN') : '未设置';

            // 更新优先级预览
            const selectedPriority = document.querySelector('input[name="priority"]:checked');
            if (selectedPriority) {
                const badgeClass = selectedPriority.value === 'low' ? 'bg-success' :
                                 selectedPriority.value === 'medium' ? 'bg-warning' : 'bg-danger';
                const badgeText = selectedPriority.value === 'low' ? '低优先级' :
                                 selectedPriority.value === 'medium' ? '中优先级' : '高优先级';
                previewPriority.className = `badge ${badgeClass}`;
                previewPriority.textContent = badgeText;
            }
        }

        // 事件监听
        nameInput.addEventListener('input', updatePreview);
        assigneeSelect.addEventListener('change', updatePreview);
        dueDateInput.addEventListener('change', updatePreview);
        priorityRadios.forEach(radio => {
            radio.addEventListener('change', updatePreview);
        });

        // 文件上传处理
        selectFilesBtn.addEventListener('click', () => fileInput.click());

        fileInput.addEventListener('change', handleFileSelect);

        // 拖放事件
        fileUploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            fileUploadArea.classList.add('bg-light');
        });

        fileUploadArea.addEventListener('dragleave', () => {
            fileUploadArea.classList.remove('bg-light');
        });

        fileUploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            fileUploadArea.classList.remove('bg-light');
            fileInput.files = e.dataTransfer.files;
            handleFileSelect({ target: fileInput });
        });

        // 处理文件选择
        function handleFileSelect(event) {
            filePreview.innerHTML = '';
            const files = event.target.files;

            if (files.length > 0) {
                fileUploadArea.querySelector('.d-flex').classList.add('d-none');

                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    const fileItem = document.createElement('div');
                    fileItem.className = 'd-flex align-items-center justify-content-between mb-2 p-3 file-preview-item bg-light rounded';
                    fileItem.innerHTML = `
                        <div class="d-flex align-items-center">
                            <i class="fas ${getFileIcon(file.name)} me-3 text-muted"></i>
                            <div>
                                <div class="small">${file.name}</div>
                                <div class="text-muted extra-small">${formatFileSize(file.size)}</div>
                            </div>
                        </div>
                        <button type="button" class="btn btn-sm btn-outline-danger rounded-circle remove-file" data-index="${i}">
                            <i class="fas fa-times"></i>
                        </button>
                    `;
                    filePreview.appendChild(fileItem);
                }
            } else {
                fileUploadArea.querySelector('.d-flex').classList.remove('d-none');
            }

            // 添加移除文件事件
            document.querySelectorAll('.remove-file').forEach(btn => {
                btn.addEventListener('click', function() {
                    const index = this.dataset.index;
                    const files = Array.from(fileInput.files);
                    files.splice(index, 1);

                    // 更新文件输入
                    const dataTransfer = new DataTransfer();
                    files.forEach(file => dataTransfer.items.add(file));
                    fileInput.files = dataTransfer.files;

                    // 重新渲染预览
                    handleFileSelect({ target: fileInput });
                });
            });
        }

        // 获取文件图标
        function getFileIcon(filename) {
            const ext = filename.split('.').pop().toLowerCase();
            const icons = {
                pdf: 'fa-file-pdf',
                doc: 'fa-file-word',
                docx: 'fa-file-word',
                xls: 'fa-file-excel',
                xlsx: 'fa-file-excel',
                ppt: 'fa-file-powerpoint',
                pptx: 'fa-file-powerpoint',
                jpg: 'fa-file-image',
                jpeg: 'fa-file-image',
                png: 'fa-file-image',
                gif: 'fa-file-image',
                zip: 'fa-file-archive',
                rar: 'fa-file-archive',
                txt: 'fa-file-alt',
                csv: 'fa-file-csv'
            };
            return icons[ext] || 'fa-file';
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 设置表单enctype
        const form = document.getElementById('taskForm');
        form.enctype = 'multipart/form-data';

        // 表单提交验证
        form.addEventListener('submit', function(e) {
            // 简单的表单验证
            if (!nameInput.value.trim()) {
                e.preventDefault();
                showAlert('请填写任务名称', 'warning');
                nameInput.focus();
                return;
            }

            if (descriptionTextarea.value.length > 500) {
                e.preventDefault();
                showAlert('任务描述不能超过500个字符', 'warning');
                descriptionTextarea.focus();
                return;
            }

            // 确保优先级有值
            const selectedPriority = document.querySelector('input[name="priority"]:checked');
            if (!selectedPriority) {
                e.preventDefault();
                showAlert('请选择任务优先级', 'warning');
                return;
            }

            // 确保负责人ID正确处理
            const assigneeSelect = document.getElementById('assignee_id');
            if (assigneeSelect.value === 'None') {
                assigneeSelect.value = ''; // 将 'None' 转换为空字符串
            }

            // 显示提交成功提示
            showAlert('任务创建成功！正在跳转...', 'success');
        });

        // 显示提示信息
        function showAlert(message, type) {
            // 创建提示元素
            const alert = document.createElement('div');
            alert.className = `alert alert-${type} alert-dismissible fade show position-fixed top-0 start-50 translate-middle-x mt-5`;
            alert.style.zIndex = '1060';
            alert.innerHTML = `
            <div class="d-flex align-items-center">
                <i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle'} me-2"></i>
                <div>${message}</div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;

            document.body.appendChild(alert);

            // 自动关闭
            setTimeout(() => {
                if (alert.parentNode) {
                    alert.remove();
                }
            }, type === 'success' ? 3000 : 5000);
        }

        // 设置默认日期为明天
        const tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);
        const formattedDate = tomorrow.toISOString().split('T')[0];
        dueDateInput.min = formattedDate;

        // 初始化预览
        updatePreview();
    });
</script>
{% endblock %}